﻿using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Drawing.Printing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Zhao.Common.Helper;
using Zhao.IServer.Log;
using Zhao.Models.DTO;
using Zhao.Models.Entity;
using Zhao.Repository.Base;
using Zhao.Repository.UnitOfWork;

namespace Zhao.Service.Log
{
    public class NotificationsServer : BaseService<Notifications>, INotificationsServer
    {
        private readonly IUnitOfWork _unitOfWork;
        public NotificationsServer(IBaseRepository<Notifications> baseDal, IUnitOfWork unitOfWork) : base(baseDal, unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<PageModel<NotificationDTO>> QueryNotiPageInfo(Expression<Func<Notifications,Venues,bool>> expressionable,int pageIndex,int pageSize)
        {
            //获取总条数
            RefAsync<int> totalCount = 0;

            //连表查询
            var list = await _Client.Queryable<Notifications>()
                .LeftJoin<Venues>((a,b)=>a.VenueID==b.VenueID)
                .WhereIF(expressionable!=null,expressionable)
                .Select((a,b)=>new NotificationDTO
                {
                    NotificationID = a.NotificationID,
                    Title = a.Title,
                    Content = a.Content,
                    PublisherID = a.PublisherID,
                    // 联表获取球馆名称，若为null显示"平台通知"
                    VenueName = b.VenueName ?? "平台通知",
                    NotificationType = a.NotificationType,
                    IsDeleted = a.IsDeleted,
                    PublishTime = a.PublishTime,
                    ExpiryTime = a.ExpiryTime,
                    Image = a.Image,
                    // 直接映射数据库中的状态字段
                    Status =a.Status
                }).ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false);

            int totalPage = (Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal())).ObjToInt();

            return new PageModel<NotificationDTO>() { count = totalCount, PageCount = totalPage, PageIndex = pageIndex, PageSize = pageSize, data = list, code = totalCount == 0 ? -1 : 0, msg = totalCount == 0 ? "未查询到任何数据" : "" };
        }

        /// <summary>
        /// 获取最新的公告信息
        /// </summary>
        /// <param name="notificationType">公告类型：1-后台通知，5-用户通知</param>
        /// <param name="venueId">球馆ID，如果为null则查询平台通知</param>
        /// <returns>最新的公告信息</returns>
        public async Task<NotificationDTO> GetLatestNotification(short notificationType)
        {
            // 查询条件：
            // 1. 状态为展示中(1)
            // 2. 未删除
            // 3. 未过期（ExpiryTime > 当前时间 或 ExpiryTime 为 null）
            // 4. 符合指定的通知类型
            // 5. 如果指定了venueId，查询该venueId的公告；否则查询平台公告(VenueID为null)
            
            var query = _Client.Queryable<Notifications>()
                //.LeftJoin<Venues>((n, v) => n.VenueID == v.VenueID)
                .Where(n => n.Status == 1)  // 展示中的公告
                .Where(n => n.IsDeleted == 0 || n.IsDeleted == null) // 未删除
                .Where(n => n.NotificationType == notificationType) // 指定类型
                .Where(n => n.ExpiryTime == null || n.ExpiryTime > DateTime.Now) // 未过期d
                .Where( n => n.VenueID == null) // 如果未指定venueId，查询平台公告
                .OrderByDescending(n => n.PublishTime) // 按发布时间降序
                .Select(n => new NotificationDTO
                {
                    NotificationID = n.NotificationID,
                    Title = n.Title,
                    Content = n.Content,
                    PublisherID = n.PublisherID,
                    VenueName = "平台通知",
                    NotificationType = n.NotificationType,
                    IsDeleted = n.IsDeleted,
                    PublishTime = n.PublishTime,
                    ExpiryTime = n.ExpiryTime,
                    Image = n.Image,
                    Status = n.Status
                });

            // 获取最新的一条记录
            return await query.FirstAsync();
        }
    }
}
